/**
 * @Description:
 * @Author: wyh19
 * @Date: 2021-05-21
 */
import debounce from 'lodash.debounce'
import { easyClone } from '@/utils'
export default {
  inject: ['formType'],
  props: {
    formKey: {
      type: String,
      default: ''
    },
    data: {
      type: Object,
      default: () => ({})
    },
    oldData: {
      type: Object,
      default: () => ({})
    },
    linkChannel: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      formData: {},
      oldFormData: null,
      ruleResults: {}
    }
  },
  computed: {
    partFormData() {
      return this.data[this.formKey]
    },
    partOldFormData() {
      return this.oldData[this.formKey]
    },
    formDisabled() {
      return this.formType === 'detail' || this.formType === 'compare'
    }
  },
  watch: {
    partFormData: {
      handler(newValue) {
        this.formData = easyClone(newValue) || {}
      },
      immediate: true
    },
    partOldFormData(newValue) {
      // 当没有老数据时，希望就得到空
      this.oldFormData = easyClone(newValue)
    }
  },
  methods: {
    /**
     * 转换select选项为比对指令需要的map类型
     * 例如: [{value:1,label:'a'}] ===> {1:a}
     */
    composeOptions(options = [], value = 'value', label = 'label') {
      const map = {}
      options.forEach(item => {
        map[item[value]] = item[label]
      })
      return map
    },
    validForm() {
      let result = false
      this.$refs['form'].validate((valid) => { result = valid })
      return result
    },
    handleValidate: debounce(function(rule, isValid) {
      // 记录表单项结果，用于判断是否所有项都通过
      this.ruleResults[rule] = isValid
      if (!isValid) {
        // 只要本项失败，则通知主表单校验失败
        this.$emit('validate', this.formKey, false)
      } else {
        let result = true
        // 如果存在未通过的项，则本表单校验未通过
        for (const key in this.ruleResults) {
          if (!this.ruleResults[key]) {
            result = false
            break
          }
        }
        // 当不存在未通过的项时，通知主表单校验通过
        if (result) {
          this.$emit('validate', this.formKey, true)
        }
      }
    }, 200)
  }
}
